/*

    This file is part of Hometree.

    Hometree is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Hometree is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with Hometree.  If not, see <http://www.gnu.org/licenses/>.

    Copyright 2011,2012 Roman Held

*/
#include <QDebug>
#include <QGLWidget>
#include "htrbranch.h"

HtrBranch::HtrBranch(float length, QObject *parent)
 : QObject(parent)
{
  mName = "root";
  mLength = length;
  mSideVector[0] = mSideVector[1] = 0;
}

HtrBranch::HtrBranch(const QString &name, float length, QObject *parent)
 : QObject(parent)
{
  mName = name;
  mLength = length;

  mSideVector[0] = (qrand() % 2000)/1000.0 - 1; // -1 .. +1
  mSideVector[1] = (qrand() % 2000)/1000.0 - 1; // -1 .. +1
}

// --------------------------------------------------------
void HtrBranch::init(const QStringList &url)
{
  Q_ASSERT(url.length() > 0);
  QStringList nextUrl = url;
  QString root = nextUrl.takeFirst();

  // Top reached?
  if (nextUrl.isEmpty()) {
    if (!mFruits.contains(root))
      mFruits << root;
    return;
  }
 
  // Is there a child?
  bool found = false;
  foreach(HtrBranch *child, mChilds) {
    if (child->name() == root) {
      child->init(nextUrl);
      found = true;
      break;
    }
  }
  
  if (!found) {
    HtrBranch *newBranch = new HtrBranch(root, mLength*0.9, this);
    newBranch->init(nextUrl);
    mChilds << newBranch;
  }
}

// --------------------------------------------------------
void HtrBranch::drawGL()
{
  float endPoint[]  = {mSideVector[0]*mLength*0.5,  mLength, mSideVector[1]*mLength*0.5 };
  glColor3f(1,0,1);
  glBegin( GL_LINES );
    glVertex3f(0,0,0);
    glVertex3f(endPoint[0], endPoint[1], endPoint[2]);
  glEnd();
 
  glPushMatrix(); 
  glTranslatef(endPoint[0], endPoint[1], endPoint[2]);
  foreach(HtrBranch *child, mChilds)
    child->drawGL();
  glPopMatrix();
}

// --------------------------------------------------------
void HtrBranch::setLength(float length)
{
  mLength = length;
  foreach(HtrBranch *child, mChilds)
    child->setLength(mLength*0.9);
}

